<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form label-width="120px">
      <el-form-item label="推荐位名称">
        <el-input v-model="adType.title" />
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate()"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { save, updateById, getById } from "@/api/adType";

export default {
  data() {
    return {
      adType: {},
      saveBtnDisabled: false, // 保存按钮是否禁用，防止表单重复提交
    };
  },

  // 页面渲染成功
  created() {
    if (this.$route.params.id) {
      this.fetchDataById(this.$route.params.id);
    }
  },

  methods: {
    saveOrUpdate() {
      this.adType.id ? this.updateData() : this.saveData();
    },

    // 新增
    saveData() {
      save(this.adType).then((response) => {
        if (response.success) {
          // 禁用保存按钮
          this.saveBtnDisabled = true;
          this.$message.success(response.message);
          this.$router.push({ path: "/ad/type-list" });
        } else {
          this.$message.error(response.message);
        }
      });
    },

    // 根据id更新记录
    updateData() {
      // teacher数据的获取
      updateById(this.adType).then((response) => {
        if (response.success) {
          this.saveBtnDisabled = true;
          this.$message.success(response.message);
          this.$router.push({ path: "/ad/type-list" });
        } else {
          this.$message.error(response.message);
        }
      });
    },

    // 根据id查询记录
    fetchDataById(id) {
      getById(id).then((response) => {
        this.adType = response.data;
      });
    },
  },
};
</script>
